package me.shiqiang.im.sever;

import me.shiqiang.im.util.RedisPipelineProcessor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.concurrent.ConcurrentLinkedQueue;

/**
 * @author cuishiqiang
 * @date 2018/1/16 下午3:16
 */
@Component
public class QueueProcessor {
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    ConcurrentLinkedQueue<RedisPipelineProcessor> queue;

    @Autowired
    StringRedisTemplate redisTemplate;

    /**
     * 每隔0.5秒，响应消息同步请求
     */
    @Scheduled(fixedRate = 100)
    public void check() {
        logger.debug("开始处理消息队列");
        redisTemplate.executePipelined((RedisCallback<Object>) connection -> {
            for (int i = 0; i < 1000; i++) {
                RedisPipelineProcessor poll = queue.poll();
                if (poll == null) {
                    return null;
                }
                poll.process(connection);
            }
            return null;
        });

    }
}
